<template>
  <div class="health-data-page">
    <van-nav-bar title="健康档案" left-arrow @click-left="goBack" />

    <!-- 1. 最新关键指标 -->
    <div class="latest-metrics-grid">
      <div class="metric-card">
        <div class="metric-label">
          <van-icon name="like-o" color="#ee0a24" /> 最新心率
        </div>
        <div class="metric-value">{{ latestMetrics.heartRate }} <span class="unit">bpm</span></div>
      </div>
      <div class="metric-card">
        <div class="metric-label">
          <van-icon name="notes-o" color="#07c160" /> 最新血压
        </div>
        <div class="metric-value">{{ latestMetrics.bloodPressure }} <span class="unit">mmHg</span></div>
      </div>
      <div class="metric-card">
        <div class="metric-label">
          <van-icon name="fire-o" color="#ff976a" /> 最新血糖
        </div>
        <div class="metric-value">{{ latestMetrics.bloodSugar }} <span class="unit">mmol/L</span></div>
      </div>
    </div>

    <!-- 2. 健康趋势图表 -->
    <van-cell-group inset title="健康趋势">
      <div class="chart-controls">
        <van-button 
          v-for="type in chartTypes" 
          :key="type.key"
          :type="activeChartType === type.key ? 'primary' : 'default'"
          size="small" 
          round
          @click="switchChart(type.key)"
        >
          {{ type.name }}
        </van-button>
      </div>
      <div ref="chartDom" class="chart-container"></div>
    </van-cell-group>

    <!-- 3. 详细数据记录 -->
    <van-cell-group inset title="详细记录">
       <div class="record-list">
         <van-empty v-if="healthRecords.length === 0" description="暂无详细记录" />
         <div v-for="record in healthRecords" :key="record.id" class="record-item">
           <div class="record-info">
             <span class="record-type">{{ record.recordType }}</span>
             <div class="record-values">
               <span class="value">{{ record.value1 }}</span>
               <span v-if="record.value2" class="value">{{ record.value2 }}</span>
               <span class="unit">{{ record.unit }}</span>
             </div>
           </div>
           <div class="record-meta">
             <span class="time">{{ record.recordedAt }}</span>
             <van-tag v-if="record.isAbnormal" type="danger" plain>异常</van-tag>
           </div>
         </div>
       </div>
    </van-cell-group>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, shallowRef } from 'vue';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, GridComponent, LegendComponent, VisualMapComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册 ECharts 组件
echarts.use([TitleComponent, TooltipComponent, GridComponent, LegendComponent, LineChart, CanvasRenderer, VisualMapComponent]);

const router = useRouter();

// --- 静态模拟数据 (来自 health_records 表) ---
const latestMetrics = ref({
  heartRate: '78',
  bloodPressure: '125/80',
  bloodSugar: '5.9',
});

const healthRecords = ref([
  { id: 1, elderlyUserId: 101, recordType: '血压', value1: '125', value2: '80', unit: 'mmHg', isAbnormal: false, recordedAt: '2023-11-28 08:30' },
  { id: 2, elderlyUserId: 101, recordType: '心率', value1: '78', value2: null, unit: 'bpm', isAbnormal: false, recordedAt: '2023-11-28 08:30' },
  { id: 3, elderlyUserId: 101, recordType: '血糖', value1: '5.9', value2: null, unit: 'mmol/L', isAbnormal: false, recordedAt: '2023-11-28 07:00' },
  { id: 4, elderlyUserId: 101, recordType: '血压', value1: '135', value2: '88', unit: 'mmHg', isAbnormal: false, recordedAt: '2023-11-27 08:35' },
  { id: 5, elderlyUserId: 101, recordType: '心率', value1: '85', value2: null, unit: 'bpm', isAbnormal: false, recordedAt: '2023-11-27 08:35' },
  { id: 6, elderlyUserId: 101, recordType: '血压', value1: '145', value2: '92', unit: 'mmHg', isAbnormal: true, recordedAt: '2023-11-26 08:20' },
  { id: 7, elderlyUserId: 101, recordType: '心率', value1: '95', value2: null, unit: 'bpm', isAbnormal: true, recordedAt: '2023-11-26 08:20' },
  // ...更多数据
]);

// --- ECharts 相关 ---
const chartDom = ref(null);
// 使用 shallowRef 避免 ECharts 实例被深度代理，提高性能
const myChart = shallowRef(null); 
const activeChartType = ref('bloodPressure');
const chartTypes = [
    { key: 'bloodPressure', name: '血压趋势' },
    { key: 'heartRate', name: '心率趋势' },
    { key: 'bloodSugar', name: '血糖趋势' },
];

const getChartOption = (type) => {
  // 筛选并准备数据
  const dates = [];
  const seriesData = {};
  
  if (type === 'bloodPressure') {
    seriesData['收缩压'] = [];
    seriesData['舒张压'] = [];
    healthRecords.value.filter(r => r.recordType === '血压').reverse().forEach(r => {
        dates.push(r.recordedAt.slice(5, 10)); // M-D
        seriesData['收缩压'].push(r.value1);
        seriesData['舒张压'].push(r.value2);
    });
  } else {
    const recordTypeMap = { heartRate: '心率', bloodSugar: '血糖' };
    const chartName = recordTypeMap[type];
    seriesData[chartName] = [];
    healthRecords.value.filter(r => r.recordType === chartName).reverse().forEach(r => {
        dates.push(r.recordedAt.slice(5, 10));
        seriesData[chartName].push(r.value1);
    });
  }

  return {
    tooltip: { trigger: 'axis' },
    legend: { data: Object.keys(seriesData), bottom: 10 },
    grid: { left: '15%', right: '10%', top: '15%', bottom: '25%' },
    xAxis: { type: 'category', boundaryGap: false, data: dates },
    yAxis: { type: 'value', axisLabel: { formatter: '{value}' } },
    series: Object.entries(seriesData).map(([name, data]) => ({
      name: name,
      type: 'line',
      smooth: true,
      data: data,
      markPoint: {
        data: [
          { type: 'max', name: '最大值' },
          { type: 'min', name: '最小值' }
        ]
      },
    })),
    // 视觉映射组件，用于标记异常值
    visualMap: {
      show: false,
      pieces: [
        { gte: 140, lte: 300, color: '#ee0a24' }, // 血压高值异常
        { gte: 90, lte: 140, color: '#ee0a24' },  // 心率高值异常
      ],
      seriesIndex: 0, // 应用到第一个系列（收缩压或心率）
    }
  };
};

const initChart = () => {
  if (chartDom.value) {
    myChart.value = echarts.init(chartDom.value);
    myChart.value.setOption(getChartOption(activeChartType.value));
  }
};

const switchChart = (type) => {
    activeChartType.value = type;
    if (myChart.value) {
        myChart.value.setOption(getChartOption(type), true);
    }
}

// --- 生命周期 ---
onMounted(() => {
  initChart();
  window.addEventListener('resize', () => myChart.value?.resize());
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', () => myChart.value?.resize());
  myChart.value?.dispose();
});

// --- 方法 ---
const goBack = () => router.back();

</script>

<style scoped>
.health-data-page {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 20px;
}

/* 1. 最新指标 */
.latest-metrics-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  padding: 16px;
}
.metric-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}
.metric-label {
  font-size: 13px;
  color: #646566;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  margin-bottom: 8px;
}
.metric-value {
  font-size: 20px;
  font-weight: bold;
  color: #323233;
}
.metric-value .unit {
  font-size: 12px;
  font-weight: normal;
  color: #969799;
  margin-left: 2px;
}

/* 2. 图表 */
.chart-controls {
  padding: 16px 16px 0 16px;
  display: flex;
  gap: 10px;
}
.chart-container {
  width: 100%;
  height: 250px;
}

/* 3. 详细记录 */
.record-list {
  padding: 0 16px 16px;
}
.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #ebedf0;
}
.record-item:last-child {
  border-bottom: none;
}
.record-type {
  font-size: 15px;
  font-weight: 500;
  color: #323233;
  margin-bottom: 6px;
}
.record-values {
  display: flex;
  align-items: baseline;
  gap: 4px;
}
.record-values .value {
  font-size: 16px;
  color: #646566;
}
.record-meta {
  text-align: right;
}
.record-meta .time {
  display: block;
  font-size: 12px;
  color: #969799;
  margin-bottom: 6px;
}
</style>